<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/8/9
 * Time: 17:02
 */

namespace app\command\company;

use app\admin\model\Company;
use app\admin\model\AdminDividend;
use app\company\model\PartnerDividend;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use app\company\model\Stat;

class DividendCompany extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('dividend:company')->setDescription('生成集团/公司分红设置')
             ->addArgument('date', Option::VALUE_REQUIRED, '日期', '');
    }


    protected function execute(Input $input, Output $output)
    {
        $output->writeln('生成集团/公司分红设置');
        $lastMonth = date('m', strtotime('-1 month'));
        $year      = date('Y');
        $dates     = date("Y-m-d", strtotime('-1 month'));
        if ($date = $input->getArgument('date')) {
            $lastMonth = date('m', strtotime($date));
            $year      = date('Y', strtotime($date));
            $dates     = date("Y-m-d", strtotime($date));
        }
        $model = new Company();
        $model->startTrans();
        try {
            //得到公司营业额
            //排除已删除公司
            $ids = Company::column('id');
            //生成集团分红设置
            if (!AdminDividend::where('date', $dates)->count()) {
                $amount = Stat::type(3)->where('year', $year)->whereIn('company_id', $ids)->where('month', $lastMonth)->sum('sales_amount');
                AdminDividend::create(['date' => $dates, 'turnover' => $amount]);
            }
            //生成公司分红设置
            $list = Stat::type(3)->where('year', $year)->whereIn('company_id', $ids)->where('month', $lastMonth)->select();
            foreach ($list as $item) {
                if (PartnerDividend::gs($item->company_id)->where('date', $dates)->count()) continue;
                PartnerDividend::create([
                    'date'       => $dates,
                    'company_id' => $item->company_id,
                    'turnover'   => $item->sales_amount,
                ]);
            }
            $model->commit();
            $output->writeln('生成集团/公司分红设置');
        } catch (\Exception $e) {
            $model->rollback();
            $output->writeln('生成集团/公司分红设置' . $e->getMessage() . $e->getLine() . $e->getFile());
        }
    }
}